import { useEffect, useState } from "react";
import styles from "./styles.module.less";
import { GetAppVersion, StartUpdate } from "@go/app/UpdateApp";
import { Icon } from "@iconify-icon/react";
import { BrowserOpenURL, Quit, WindowMinimise } from "@runtime";
import { Dropdown, message, Image, Modal } from "antd";
import type { MenuProps } from "antd";
import {
  SettingDropdownEnum,
  SettingDropdownIcon,
  SettingDropdownList,
} from "@/constant/title";
import appicon from "@/assets/images/appicon.png";
import { useMainStore } from "@/store/mainStore";
import { useShallow } from "zustand/react/shallow";
import SettingModal from "./tsx/settingModal";
import { http } from "@/constant/status";
import { GetBaseAddress } from "@go/app/App";
import { useCollectStore } from "@/store/collectStore";

const TitleBar = () => {
  const { sideTab, appInfo, currentHwnd, settingModalVisible } = useMainStore(
    useShallow((state) => ({
      sideTab: state.sideTab,
      appInfo: state.appInfo,
      currentHwnd: state.currentHwnd,
      settingModalVisible: state.settingModalVisible,
    }))
  );
  const { isInput, isStart } = useCollectStore(
    useShallow((state) => ({
      isInput: state.isInput,
      isStart: state.isStart,
    }))
  );

  const list: MenuProps["items"] = SettingDropdownList[0].map((item) => ({
    key: item.id,
    label: item.label,
    icon: <Icon icon={SettingDropdownIcon[1][item.id]} width={14} />,
    disabled:
      item.id === SettingDropdownEnum.Preference && (isInput || isStart),
  }));

  const listAll = list.concat([
    {
      type: "divider",
    },
    {
      key: "update_base",
      label: "更新基址",
      icon: <Icon icon="carbon:foundation-model" width={14} />,
      disabled: !currentHwnd,
    },
  ]);

  const updateBaseAddress = async () => {
    message.loading("正在获取基址...", 0);
    try {
      await GetBaseAddress(currentHwnd as number);
    } catch (err) {
      setTimeout(() => {
        message.error(err as string);
      }, 200);
    } finally {
      message.destroy();
    }
  };

  const dropdownClick: MenuProps["onClick"] = ({ key }) => {
    switch (key) {
      case SettingDropdownEnum.Preference:
        useMainStore.setState({ settingModalVisible: true });
        break;
      case SettingDropdownEnum.CheckUpdate:
        checkUpdate();
        break;
      case SettingDropdownEnum.AddGroup:
        BrowserOpenURL(appInfo.group_chat_url);
        break;
      case "update_base":
        updateBaseAddress();
        break;
      default:
        break;
    }
  };

  async function checkUpdate() {
    useMainStore.setState({ appLoading: true });
    try {
      const res = await GetAppVersion(
        appInfo.download_url,
        appInfo.pwd,
        appInfo.file_index
      );
      if (res.code !== http.StatusOK) {
        message.error(res.msg);
        return;
      }
      if (Number(res.data?.new_version) <= Number(appInfo.version)) {
        message.info("当前已是最新版本");
        return;
      }
      Modal.confirm({
        title: "版本更新",
        icon: null,
        content: `检测到新版本(v${res.data?.new_version})，是否立即更新？`,
        okText: "确认",
        cancelText: "取消",
        async onOk() {
          const res = await StartUpdate();
          if (res.code !== http.StatusOK) {
            message.error(res.msg);
          }
        },
      });
    } catch (err) {
      message.error(`检查更新失败: ${err}`);
    } finally {
      useMainStore.setState({ appLoading: false });
    }
  }

  return (
    <div
      className={styles.titleBar}
      style={{
        "--wails-draggable": "drag",
      }}
    >
      <div className={styles.appName}>
        <Image width={20} preview={false} src={appicon} />
        <span
          style={{
            "--wails-draggable": "no-drag",
          }}
        >
          {appInfo.version
            ? `${appInfo.app_name}v${appInfo.version}`
            : appInfo.app_name}
        </span>
      </div>
      <div
        className={styles.ctrlIcons}
        style={{
          "--wails-draggable": "no-drag",
        }}
      >
        <div className={styles.icon}>
          <Dropdown
            menu={{
              items: ["/fish", "/collect"].includes(sideTab) ? listAll : list,
              onClick: dropdownClick,
            }}
            trigger={["hover"]}
            placement="bottomLeft"
            arrow={{ pointAtCenter: true }}
          >
            <Icon icon="ep:setting" />
          </Dropdown>
        </div>
        <div className={styles.icon} onClick={WindowMinimise}>
          <Icon icon="fluent:minimize-24-regular" />
        </div>
        <div className={styles.icon} onClick={Quit}>
          <Icon icon="material-symbols:close" />
        </div>
      </div>
      <SettingModal
        open={settingModalVisible}
        closeModal={() => {
          useMainStore.setState({ settingModalVisible: false });
        }}
      />
    </div>
  );
};

export default TitleBar;
